package com.shiro;

import com.service.registerService.impl.RegisterImpl;
import com.service.registerService.service.RegisterService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/**
 * Created by CHUMI on 2017/8/8.
 */
@Controller
public class LoginController {
    //
    @Autowired
    RegisterImpl registerServiceImpl;
    @RequestMapping("/login")
    public  String login(@RequestParam("userName") String userName,@RequestParam("password") String password){
//        if("admin".equals(userName) && "admin".equals(password)){
//            return  "s";
//        }
        //获取subject实例
        Subject scurrentUser = SecurityUtils.getSubject();
        //是否登录
        if(scurrentUser.isAuthenticated()==false){
            UsernamePasswordToken token=new UsernamePasswordToken(userName,password);
            try {
                scurrentUser.login(token);
                return "s";
            }catch (AuthenticationException e){
                System.out.println("登录失败");
                return "abc";
            }

        }else{
            return "s";
        }

    }
    @RequestMapping("/register")
    @ResponseBody
    public String register(@RequestParam("userName") String userName,@RequestParam("password") String password){
      String s="fail";
        //加密
        String obj = new SimpleHash("MD5", password,userName , 1024).toString();
        registerServiceImpl.save(userName,obj);
        s="scuess";
        return s;
  }
    @RequestMapping("/loginout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout(); // session 会销毁，在SessionListener监听session销毁，清理权限缓存
            System.out.println("登出");
            System.out.println("subject"+subject);
            return  "login";
        }else{
            return "cc";
        }
    }
}
